﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Threading;
using System.Diagnostics;
using System.IO.Compression;


namespace AutoUpdater
{
    public partial class MainForm : Form
    {
        private WebClient client;
        private string URl;
        private string fileName;
        private string path;
        private const string applicationFile = "Givenchy";

        public MainForm(string url)
        {
            InitializeComponent();

            this.URl = url;
            client = new WebClient();
            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
            client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
            client.Proxy = WebRequest.DefaultWebProxy;
            client.Proxy.Credentials = new NetworkCredential();

            this.Hide();
            //Thread thread = new Thread(UpdateFile);
            //Thread.Sleep(15000);
            //thread.Start();
            UpdateFile();
        }

        public MainForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 下载完成调用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            label1.Text = "文件接收完成";
            //UnZip();
            RunUpdate();
        }

        /// <summary>
        /// 下载进度条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            this.progressBar1.Value = e.ProgressPercentage;
        }

        /// <summary>
        /// 解压压缩包，格式必须是*.zip,否则不能解压
        /// 因为是调用Windows内部api进行解压，只能够识别zip压缩包
        /// 必须添加C:\WINDOWS\system32\shell32.dll的引用
        /// </summary>
        //private void UnZip()
        //{
        //    try
        //    {
        //        Shell32.ShellClass sc = new Shell32.ShellClass();
        //        Shell32.Folder SrcFolder = sc.NameSpace(this.path + @"\" + this.fileName);
        //        Shell32.Folder DestFolder = sc.NameSpace(this.path);
        //        Shell32.FolderItems items = SrcFolder.Items();
        //        DestFolder.CopyHere(items, 20);
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show(ex.Message);
        //    }
        //}

        /// <summary>
        /// 获取下载文件夹地址及解压文件存放地址
        /// 此地址默认为C:\Documents and Settings\当前用户名\Local Settings\Temp 文件夹
        /// </summary>
        /// <returns></returns>
        private string GetTempFolder()
        {
            string folder = System.Environment.GetEnvironmentVariable("TEMP");
            return new DirectoryInfo(folder).FullName;
        }

        /// <summary>
        /// 开始下载文件
        /// </summary>
        private void UpdateFile()
        {
            this.Hide();
            //如果临时文件夹存在setup安装文件，就直接调用安装文件
            //if (File.Exists(GetTempFolder() + @"\" + applicationFile + ".exe"))
            //{
            //    label1.Text = "开始下载文件...";
            //    this.progressBar1.Value = this.progressBar1.Maximum;
            //    label1.Text = "文件接收完成";
            //    RunUpdate();
            //}
            ////如果临时文件夹不存在setup安装文件，就从网络下载
            //else
            //{
            RemoveSetupFile();
            StartDownload();
            //RunUpdate();
            //}
        }

        /// <summary>
        /// 清除旧有已下载的安装文件
        /// </summary>
        private static void RemoveSetupFile()
        {
            try
            {
                string temp = System.Environment.GetEnvironmentVariable("TEMP");
                string folder = new DirectoryInfo(temp).FullName;
                if (File.Exists(folder + @"\" + applicationFile + ".exe"))
                {
                    File.Delete(folder + @"\" + applicationFile + ".exe");
                }

            }
            catch { }
        }


        /// <summary>
        /// 开始下载
        /// </summary>
        private void StartDownload()
        {
            fileName = URl.Substring(URl.LastIndexOf("/") + 1, URl.Length - URl.LastIndexOf("/") - 1);
            path = GetTempFolder();

            try
            {
                WebRequest myre = WebRequest.Create(URl);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }

            try
            {
                label1.Text = "开始下载文件...";
                client.DownloadFileAsync(new Uri(URl), path + @"\" + fileName);

            }
            catch (WebException exp)
            {
                label1.Text = exp.Message;
            }
        }


        /// <summary>
        /// 下载完毕，开始执行更新程序
        /// </summary>
        private void RunUpdate()
        {
            try
            {
                foreach (Process p in Process.GetProcesses())
                {
                    if (p.ProcessName.ToLower().StartsWith("givenchy"))
                    {
                        {
                            p.Kill();
                        }
                    }
                } 
            }
            catch (Exception ex)
            {
                MessageBox.Show("Kill Windows : " + ex.Message);
            }

            try
            {

                File.Copy(GetTempFolder() + @"\" + applicationFile + ".exe", Application.StartupPath + @"\" + applicationFile + ".exe", true);

                System.Diagnostics.Process.Start(Application.StartupPath + @"\" + applicationFile + ".exe");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Run Update : " + ex.Message);
            }
            finally
            {
                this.Close();
            }
        }

        /// <summary>
        /// 重载WindProc判断点击关闭按钮(X)时，隐藏程序界面
        /// </summary>
        /// <param name="msg"></param>
        protected override void WndProc(ref Message msg)
        {
            const int WM_SYSCOMMAND = 0x0112;
            const int SC_CLOSE = 0xF060;

            if (msg.Msg == WM_SYSCOMMAND && ((int)msg.WParam == SC_CLOSE))
            {
                this.Hide();
                return;
            }
            base.WndProc(ref msg);
        }

        /// <summary>
        /// 双击图标弹出界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void icon_notify_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            this.Hide();
        }

    }

}
